package com.example.night.service.ApiService;

import com.example.night.data.Order.Order;
import com.example.night.data.Order.OrderPackage;
import com.example.night.data.Order.OrderResponse;
import com.example.night.service.ApiService.Token.TokenService;
import com.example.night.service.ApiService.Token.TokenUpdatedEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.jar.JarException;

@Slf4j
@Service
public class OrderService {

    private static final String API_URL = "https://api.jiutool.com/institutionHomeTwo/order/es_lists";
    private static final Logger logger = LoggerFactory.getLogger(InfluencerSummaryService.class);

    private final RestTemplate restTemplate;
    private final TokenService tokenService;
    private final ObjectMapper objectMapper;
    private final Lock lock = new ReentrantLock();
    private String token;


    public OrderService(RestTemplate restTemplate, TokenService tokenService, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.tokenService = tokenService;
        this.objectMapper = objectMapper;
        token = tokenService.getToken();
    }
    public int getFlowpointFlag(String flow_point) {
        int flag = -1;  // 默认值，表示无效的 flow_point
        switch (flow_point) {
            case "PAY_SUCC":
                flag = 0;  // PAY_SUCC
                break;
            case "REFUND":
                flag = 1;  // SETTLE
                break;
            case "SETTLE":
                flag = 2;  // REFUND
                break;
            case "CONFIRM":
                flag = 3;  // CONFIRM
                break;
            default:
                flag = -1;  // 如果没有匹配到，返回 -1
                break;
        }
        return flag;
    }
    public String getFlowpoint(int flag) {
        String flow_point = "";
        switch (flag) {
            case 0:
                flow_point = "PAY_SUCC"; //支付完成
                break;
            case 1:
                flow_point = "REFUND";  //退款
                break;
            case 2:
                flow_point = "SETTLE";  //结算
                break;
            case 3:
                flow_point = "CONFIRM"; //确认收货
                break;
            default:
                flow_point = "";
                break;
        }
        return flow_point;
    }
    @EventListener
    public void handleTokenUpdated(TokenUpdatedEvent event) {
        token = event.getNewToken();
    }

    public Map<String, Object> fetchOrders(String startTime, String endTime, int page, String title, int flow_point, int extend_type, String promoterId) {
        try {
            token = tokenService.getToken();
            if (token == null || token.isEmpty()) {
                logger.error("获取达人数据失败：Token 为空，请检查登录状态");
                return Map.of(
                        "success", false,
                        "message", "未登录"
                );
            }
            // 构建请求 URL
            String url = UriComponentsBuilder.fromHttpUrl(API_URL)
                    .queryParam("page", page)
                    .queryParam("limit", 10)
                    .queryParam("time_field", "pay_success_time")
                    .queryParam("start_time", startTime)
                    .queryParam("end_time", endTime)
                    .queryParam("title", title)
                    .queryParam("flow_point", flow_point == 4 ? "" : getFlowpoint(flow_point))
                    .queryParam("order_id", "")
                    .queryParam("author_account", promoterId)
                    .queryParam("drsw_account_id", "")
                    .queryParam("zsyy_account_id", "")
                    .queryParam("extend_type", extend_type == 3 ? "" : extend_type)
                    .queryParam("is_drsw", "")
                    .queryParam("is_zsyy", "")
                    .queryParam("f_institution_name", "")
                    .queryParam("except_status", "")
                    .queryParam("type", "in")
                    .toUriString();

            // 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + token);  // 设置 Authorization 请求头
            headers.set("X-Csrf-Token", token);     // 设置 CSRF Token
            headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 构造 HTTP 请求
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);

//            log.info("请求第 {} 页订单数据: {}", page, url);
            // 发送 GET 请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
//            log.info("API 返回数据: {}", response.getBody());

            // 解析 JSON 响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                OrderResponse orderResponse = null;
                try {
                    orderResponse = objectMapper.readValue(response.getBody(), OrderResponse.class);
                }catch (JsonProcessingException e) {
                    System.out.println(url);
                    System.out.println(response.getBody());
                }

                if (orderResponse.getData() != null) {
                    List<Order> orders = orderResponse.getData().getData();
                    List<OrderPackage> orderPackages = new ArrayList<>();
                    int lastPage = orderResponse.getData().getLastPage();
                    for (Order order :orders) {
                        OrderPackage orderPackage = new OrderPackage();

                        orderPackage.setRelateOrderNo(order.getOrderId());

                        orderPackage.setRelateProductImg(order.getProductImg());
                        orderPackage.setRelateProductName(order.getProductName());
                        orderPackage.setRelateProductId(order.getProductId());

                        orderPackage.setPromoterId(order.getFInstitutionId() != "" ? order.getFInstitutionId() : order.getAuthorShortId());
                        orderPackage.setPromoteName(order.getFInstitutionName() != "" ? order.getFInstitutionName() : order.getAuthorAccount());

                        orderPackage.setOrderPayTime(order.getPaySuccessTime());
                        orderPackage.setOrderConfirmTime(order.getSettleTime());
                        orderPackage.setStatus(getFlowpointFlag(order.getFlowPoint()));

                        orderPackage.setSysRelateServiceMoneyIn(order.getInEstimatedCommission());
                        orderPackage.setSysSettleMoney(order.getTotalPayAmount());

                        orderPackages.add(orderPackage);
                    }

                    return Map.of(
                            "success", true,
                            "message", "获取成功",
                            "totalOrders", orderPackages.size(),
                            "orders", orderPackages,
                            "lastpage", lastPage
                    );
                }
            } else {
                log.error("获取订单数据失败，状态码: {}", response.getStatusCode());
            }

        } catch (Exception e) {
            log.error("获取订单数据请求失败", e);
            tokenService.login("15651616098", "zhutao123");
        }
        return Map.of(
                "success", false,
                "message", "获取失败"
        );
    }
}
